/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.handler;

import com.googlecode.asyncmail.common.DSNStatus;
import com.googlecode.asyncmail.smtp.SMTPResponse;
import com.googlecode.asyncmail.smtp.SMTPResponseImpl;
import com.googlecode.asyncmail.smtp.SMTPRetCode;
import com.googlecode.asyncmail.smtpserver.SMTPSession;
import com.googlecode.asyncmail.smtpserver.core.CommandHandler;
import com.googlecode.asyncmail.smtpserver.hook.HeloHook;
import com.googlecode.asyncmail.smtpserver.hook.HookResult;
import com.googlecode.asyncmail.smtpserver.hook.HookResultHook;
import com.googlecode.asyncmail.smtpserver.hook.HookReturnCode;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Handles HELO command
 */
public class HeloCmdHandler extends AbstractHookableCmdHandler implements
        CommandHandler {

    public final static String CURRENT_HELO_NAME = "CURRENT_HELO_NAME";

    public final static String CURRENT_HELO_MODE = "CURRENT_HELO_MODE"; // HELO
                                                                        // or

    // EHLO

    /**
     * The name of the command handled by the command handler
     */
    private final static String COMMAND_NAME = "HELO";

    private HookResultHook cleanupHook;

    /**
     * @see com.googlecode.asyncmail.smtpserver.core.CommandHandler#getImplCommands()
     */
    public Collection<String> getImplCommands() {
        Collection<String> implCommands = new ArrayList<String>();
        implCommands.add(COMMAND_NAME);

        return implCommands;
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.handler.AbstractHookableCmdHandler#doCoreCmd(com.googlecode.asyncmail.smtpserver.IoSession,
     *      java.lang.String, java.lang.String)
     */
    protected SMTPResponse doCoreCmd(SMTPSession session, String command,
            String parameters) {
        session.getConnectionState().put(CURRENT_HELO_MODE, COMMAND_NAME);
        StringBuffer response = new StringBuffer();
        response.append(session.getConfigurationData().getHelloName()).append(
                " Hello ").append(parameters).append(" (").append(
                session.getRemoteIPAddress()).append(")");
        return new SMTPResponseImpl(SMTPRetCode.MAIL_OK, response);
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.handler.AbstractHookableCmdHandler#doFilterChecks(com.googlecode.asyncmail.smtpserver.IoSession,
     *      java.lang.String, java.lang.String)
     */
    protected SMTPResponse doFilterChecks(SMTPSession session, String command,
            String parameters) {
        // TODO we have to cleanup here:
        session.resetState();

        if (parameters == null) {
            return new SMTPResponseImpl(SMTPRetCode.SYNTAX_ERROR_ARGUMENTS,
                    DSNStatus.getStatus(DSNStatus.PERMANENT,
                            DSNStatus.DELIVERY_INVALID_ARG)
                            + " Domain address required: " + COMMAND_NAME);
        } else {
            // store provided name
            session.getConnectionState().put(CURRENT_HELO_NAME, parameters);
            return null;
        }
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.handler.AbstractHookableCmdHandler#getHookInterface()
     */
    protected Class<?> getHookInterface() {
        return HeloHook.class;
    }

    /**
     * @see com.googlecode.asyncmail.smtpserver.handler.AbstractHookableCmdHandler#callHook(java.lang.Object,
     *      com.googlecode.asyncmail.smtpserver.IoSession, java.lang.String)
     */
    protected HookResult callHook(Object rawHook, SMTPSession session,
            String parameters) {
        return ((HeloHook) rawHook).doHelo(session, parameters);
    }

    @Override
    protected HookResultHook getCleanupHook() {
        if (cleanupHook == null) {
            cleanupHook = new HookResultHook() {

                /**
                 * @see com.googlecode.asyncmail.smtpserver.hook.HookResultHook#onHookResult(com.googlecode.asyncmail.smtpserver.SMTPSession,
                 *      com.googlecode.asyncmail.smtpserver.hook.HookResult,
                 *      java.lang.Object)
                 */
                public HookResult onHookResult(SMTPSession session,
                        HookResult result, Object object) {
                    if (result.getResult() == HookReturnCode.DENY
                            || result.getResult() == HookReturnCode.DENYSOFT) {
                        session.getConnectionState().remove(
                                SMTPSession.CURRENT_HELO_MODE);
                        session.getConnectionState().remove(
                                SMTPSession.CURRENT_HELO_NAME);
                    }
                    return result;
                }

            };
        }
        return cleanupHook;
    }

}
